#include <iostream>

#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>

using namespace std;

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cout << "udp_client server_ip server_port" << endl;
        return 1;
    }

    int sockfd = 0;
    int n = socket(AF_INET, SOCK_DGRAM, 0);
    if (n > 0)
    {
        sockfd = n;
    }
    else
    {
        exit(1);
    }
    u_int16_t port = atoi(argv[2]);
    struct sockaddr_in serveraddr;
    serveraddr.sin_family = AF_INET;
    serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
    serveraddr.sin_port = htons(port);

    while (true)
    {
        cout<<"client# ";
        string in;
        getline(cin, in);
        sendto(sockfd, in.c_str(), in.size(), 0, (sockaddr *)&serveraddr, sizeof(serveraddr));

        struct sockaddr_in raddr;
        socklen_t raddr_len = sizeof(raddr);
        char rbuf[1024];
        int n = recvfrom(sockfd, rbuf, sizeof(rbuf), 0, (sockaddr *)&raddr, &raddr_len);
        if (n > 0)
        {
            rbuf[n] = '\0';
            cout << rbuf << endl;
        }
        else
        {
            cerr<<"recvfrom error"<<endl;
        }
    }
    return 0;
}